package com.liu.bean.params;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Data
public class Page {

    @ApiModelProperty(value = "当前第几页，默认第一页")
    int page;
    @ApiModelProperty(value = "每页记录数，默认10",required = false)
    int pageSize;


    /**
     * 将javabean转换为Map
     * @return
     */
    public Map toMap() {
        //先转换父类
        Map parentMap = convertToMap(this.getClass().getSuperclass());
        //获取当前类
        Map childMap = convertToMap(this.getClass());
        parentMap.putAll(childMap);
        return parentMap;
    }



    /**
     * 转换map
     * @param clazz
     * @return
     */
    Map convertToMap(Class clazz) {
        Map map = new HashMap();
        //利用反射获取当前类的所有字段
        Field[] fields = clazz.getDeclaredFields();
        //遍历字段
        for (Field f : fields) {
            //获取字段名称
            String key = f.getName();
            //获取字段值
            Object value = null;
            try {
                value = f.get(this);
            } catch (IllegalAccessException e) {
                throw new RuntimeException();
            }
            map.put(key,value);
        }
        return map;
    }


}
